import { zhReg } from '@/utils/utils';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { history } from 'umi';
import { stringify } from 'querystring';
import { message } from 'antd';
import { useRef } from 'react';
import type { ModifyPassword } from '../types';
import { updatePassword } from '../service';
import { logout } from '@/services/user/api';

const loginOut = async () => {
  await logout();
  const { query = {}, pathname } = history.location;
  const { redirect } = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname,
      }),
    });
  }
};
export default (props: { id: string }) => {
  const formRef = useRef<FormInstance>();
  return (
    <ModalForm<ModifyPassword>
      title="更改密码"
      layout="horizontal"
      width="35vw"
      formRef={formRef}
      modalProps={{
        destroyOnClose: true,
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={<a>更改密码</a>}
      onFinish={async (values) => {
        const res = await updatePassword(props.id, {
          oldPass: values.oldPass,
          password: values.password,
        });
        if (res.success) {
          message.success({
            content: res.message,
            key: 'modify_pass',
          });
          formRef.current?.resetFields();
          // eslint-disable-next-line no-restricted-globals
          location.reload();
          await loginOut();
          return true;
        }
        message.error({
          content: res.message,
          key: 'modify_pass',
        });
        return false;
      }}
    >
      <ProFormText.Password
        required
        label="原有密码"
        placeholder="请输入原有密码"
        name="oldPass"
        initialValue=""
      />
      <ProFormText.Password
        required
        label="新的密码"
        placeholder="请输入新的密码"
        name="password"
        initialValue=""
        rules={[
          {
            validator: (_, val) => {
              if (zhReg.test(val)) return Promise.reject(new Error('密码不符合要求'));
              if (!val || val.length < 6) return Promise.reject(new Error('密码长度不得低于6位'));
              if (val === '123456') return Promise.reject(new Error('密码强度过低'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormText.Password
        required
        label="确认密码"
        placeholder="请再次输入新的密码"
        name="confirm"
        dependencies={['password']}
        initialValue=""
        rules={[
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致！'));
            },
          }),
        ]}
      />
    </ModalForm>
  );
};
